import { ref } from "vue";
import { Snackbar } from "@varlet/ui";

export default function useUploads() {
  const loading = ref<boolean>(false);
  // 分片
  function createChunks(file) {
    const SIZE = 1024 * 1024 * 10; // 默认10M
    const { size, name, type } = file;
    let current = 0;
    let partLists = [];
    // 进行切片
    while (current < size) {
      let chunk = file.slice(current, current + SIZE);
      partLists.push({ chunk, size: chunk.size });
      current += SIZE;
    }
    return partLists;
  }
  // 计算哈希 其实可以后端计算主要为了使用一下worker
  function calculateHash(partList) {
    return new Promise((resolve) => {
      // http://47.104.71.122:8080
      let worker = new Worker(new URL("../../utils/hash.js", import.meta.url));
      worker.postMessage({ partList });
      worker.onmessage = (event) => {
        let { hash } = event.data;
        if (hash) {
          resolve(hash);
        }
      };
    });
  }

  return {
    createChunks,
    calculateHash,
  };
}
